package com.yjf.ljr.util;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.RechargeActivity;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.RechargeTestDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PaymentCipherDialog extends Dialog {

	public PaymentCipherDialog(Context context) {
		super(context);

	}

	public PaymentCipherDialog(Context context, int theme) {
		super(context, theme);
	}

	public static class Builder {
		private RechargeTestTask RechargeTestTask;
		private Context context;
		private String title;
		private String paypassUrl;
		// private CookieManager mCookieManager;
		private String bankCode;
		private String rechargeAmount;
		private String token;
		private String positiveButtonText;
		private String negativeButtonText;
		private View contentView;
		private ProgressBar mProgressBar;
		private WebView mwebView;
		private DialogInterface.OnClickListener positiveButtonClickListener;
		private DialogInterface.OnClickListener negativeButtonClickListener;
		private boolean resultFlag = false;
		private CookieManager mCookieManager;
		boolean alertDialogFlag = false;
		private boolean firstLoadFlag = false;
		private LinearLayout mLlPaymentCipher;

		public Builder(Context context) {
			this.context = context;

		}

		public Builder setPaypassUrl(String paypassUrl) {
			this.paypassUrl = paypassUrl;
			this.firstLoadFlag = false;
			return this;
		}

		/**
		 * Set the Dialog message from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setPaypassUrl(int paypassUrl) {
			this.paypassUrl = (String) context.getText(paypassUrl);
			return this;
		}

		public Builder setBankCode(String bankCode) {
			this.bankCode = bankCode;
			return this;
		}

		public Builder setBankCode(int bankCode) {
			this.bankCode = (String) context.getText(bankCode);
			return this;
		}

		public Builder setRechargeAmount(String rechargeAmount) {
			this.rechargeAmount = rechargeAmount;
			return this;
		}

		public Builder setRechargeAmount(int rechargeAmount) {
			this.rechargeAmount = (String) context.getText(rechargeAmount);
			return this;
		}

		public Builder setToken(String token) {
			this.token = token;

			return this;
		}

		public Builder setToken(int token) {
			this.token = (String) context.getText(token);
			return this;
		}

		/**
		 * Set the Dialog title from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			this.title = (String) context.getText(title);
			return this;
		}

		/**
		 * Set the Dialog title from String
		 * 
		 * @param title
		 * @return
		 */

		public Builder setTitle(String title) {
			this.title = title;
			return this;
		}

		public Builder setContentView(View v) {
			this.contentView = v;
			return this;
		}

		/**************** 得到屏幕高度 *******************/

		/**
		 * Set the positive button resource and it's listener
		 * 
		 * @param positiveButtonText
		 * @return
		 */
		public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) {
			this.positiveButtonText = (String) context.getText(positiveButtonText);
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) {
			this.positiveButtonText = positiveButtonText;
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) {
			this.negativeButtonText = (String) context.getText(negativeButtonText);
			this.negativeButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) {
			this.negativeButtonText = negativeButtonText;
			this.negativeButtonClickListener = listener;
			return this;
		}

		String cookieString;

		@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
		public PaymentCipherDialog create() {
			/***************************/
			resultFlag = false;
			if (Build.VERSION.SDK_INT >= 11) {
				StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
						.detectNetwork().penaltyLog().build());
				StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
						.detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
			}

			/***************************/

			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// instantiate the dialog with the custom Theme
			final PaymentCipherDialog dialog = new PaymentCipherDialog(context, R.style.Dialog);
			View layout = inflater.inflate(R.layout.activity_paymentcipher_dialog, null);
			dialog.addContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			// set the dialog title
			((TextView) layout.findViewById(R.id.title)).setText(title);
			mwebView = ((WebView) layout.findViewById(R.id.wvPaymentCipher));
			mLlPaymentCipher = ((LinearLayout) layout.findViewById(R.id.llPaymentCipher));

			mProgressBar = ((ProgressBar) layout.findViewById(R.id.progressBar));
			// set the confirm button
			if (positiveButtonText != null) {
				((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);
				if (positiveButtonClickListener != null) {
					((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
						}
					});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.positiveButton).setVisibility(View.GONE);
			}
			// set the cancel button
			if (negativeButtonText != null) {
				((Button) layout.findViewById(R.id.negativeButton)).setText(negativeButtonText);
				if (negativeButtonClickListener != null) {
					((Button) layout.findViewById(R.id.negativeButton)).setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
						}
					});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.negativeButton).setVisibility(View.GONE);
			}

			// set the content message
			if (paypassUrl != null) {

				WebSettings settings = mwebView.getSettings();
				mwebView.loadUrl(paypassUrl);

				int scale = (int) context.getResources().getDimension(R.dimen.webview_scale);
				mwebView.setInitialScale(scale);
				mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
				settings.setSupportZoom(false);
				settings.setBuiltInZoomControls(false);
				settings.setDomStorageEnabled(true);

				settings.setAllowFileAccess(true);

				settings.setAppCacheEnabled(true);

				settings.setJavaScriptEnabled(true);
				mwebView.getSettings().setUseWideViewPort(true);
				settings.setCacheMode(WebSettings.LOAD_DEFAULT);

				settings.setUseWideViewPort(false);
				settings.setLoadWithOverviewMode(false);
				settings.supportMultipleWindows();
				settings.setDatabaseEnabled(true);
				CookieSyncManager.createInstance(context);
				settings.setJavaScriptCanOpenWindowsAutomatically(true);

				/*******************/
				mwebView.setWebChromeClient(new WebChromeClient());

				mwebView.setWebViewClient(new WebViewClient() {

					@Override
					public void onPageFinished(WebView view, String url) {
						// TODO Auto-generated method stub
						firstLoadFlag = true;

						int pagefinishResult = url.indexOf("isSuccess=true");
						/*
						 * if (!resultFlag) {
						 * mProgressBar.setVisibility(View.GONE); }
						 */
						// if (-1 != pagefinishResult) {
						// dialog.dismiss();
						// // mProgressBar.setVisibility(View.GONE);
						//
						// if (!RechargeActivity.mDialogFlag) {
						// RechargeActivity.instance.setResult(Activity.RESULT_OK);
						// RechargeActivity.instance.finish();
						// }
						//
						// }
						if (!resultFlag) {
							mProgressBar.setVisibility(View.GONE);
							mLlPaymentCipher.setVisibility(View.GONE);
						}
						mwebView.clearCache(true);
						mwebView.clearHistory();
						super.onPageFinished(view, url);

					}

					@Override
					public void onPageStarted(WebView view, String url, Bitmap favicon) {
						// TODO Auto-generated method stub
						super.onPageStarted(view, url, favicon);
						/*
						 * CookieSyncManager.createInstance(context);
						 * mCookieManager = CookieManager.getInstance();
						 * cookieString = mCookieManager.getCookie(url);
						 */
						mProgressBar.setVisibility(View.VISIBLE);
						mLlPaymentCipher.setVisibility(View.VISIBLE);
						int cancelResult = url.indexOf("yjfPayPassewordCancelUrl");
						int ReturnResult = url.indexOf("yjfPayPassewordReturnUrl");
						int determineResult = url.indexOf("isSuccess=true");
						String mFailStr = null;
						RechargeTestDataClass dc = new RechargeTestDataClass();
						if (-1 != cancelResult && -1 == ReturnResult && firstLoadFlag) {
							firstLoadFlag = false;
							dialog.dismiss();

						} else if (-1 != determineResult && -1 == cancelResult) {
							resultFlag = true;
							String paytk = "";
							int startIndex = url.indexOf("paytk=");
							int endIndex = url.indexOf("&_t");
							if (!TextUtils.isEmpty(url) && startIndex != -1 && endIndex != -1) {
								paytk = url.substring(startIndex + 6, endIndex).toString();
								mwebView.stopLoading();
								new RechargeTestTask(bankCode, rechargeAmount, paytk, token, dialog).execute();

								// RequestObject requestObject = new
								// RequestObject();
								// requestObject.method = "dkChargeSubmit";
								// requestObject.map.put("bankCode", bankCode);
								// requestObject.map.put("rechargeAmount",
								// rechargeAmount);
								// requestObject.map.put("paytk", paytk);
								// requestObject.map.put("token", token);
								// String requrestUrl =
								// RequestBuilder.build(requestObject);
								// resultFlag = true;
								// mProgressBar.setVisibility(View.VISIBLE);
								// try {
								// IjConnect.doRequest(requrestUrl, dc);
								//
								// if (dc.code == null) {
								// mFailStr = "获取数据异常，请稍后重试";
								// } else if
								// (!dc.code.equals(CommonData.RESULT_SUCCESS))
								// {
								// mFailStr = dc.msg;
								// }
								// } catch (Exception e) {
								// mFailStr = "获取数据异常，请稍后重试";
								// e.printStackTrace();
								// }
								// mProgressBar.setVisibility(View.GONE);
								// if (!(TextUtils.isEmpty(mFailStr))) {// fail
								// Toast.makeText(context, mFailStr,
								// Toast.LENGTH_LONG).show();
								// // RechargeActivity.mDialogFlag = true;
								// // RechargeActivity.mResult = mFailStr;
								// dialog.dismiss();
								// } else {// success
								// Toast.makeText(context, dc.msg,
								// Toast.LENGTH_LONG).show();
								// alertDialogFlag = true;
								// mwebView.stopLoading();
								// dialog.dismiss();
								// RechargeActivity.instance.setResult(Activity.RESULT_OK);
								// RechargeActivity.instance.finish();
								// mProgressBar.setVisibility(View.GONE);
								// mwebView.clearCache(true);
								// mwebView.clearHistory();
								// }
							}

						}
					}
				});

			} else if (contentView != null) {
				// if no message set // add the contentView to the dialog body
				((WebView) layout.findViewById(R.id.wvPaymentCipher)).removeAllViews();
				((WebView) layout.findViewById(R.id.wvPaymentCipher)).addView(contentView, new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			}

			dialog.setContentView(layout);
			return dialog;
		}

		class RechargeTestTask extends AsyncTask<Void, Void, Void> {
			private String bankCode;
			private String rechargeAmount;
			private String paytk;
			private String token;
			PaymentCipherDialog dialog;
			private String mFailStr;
			RechargeTestDataClass dc = new RechargeTestDataClass();

			public RechargeTestTask(String bankCode, String rechargeAmount, String paytk, String token,
					PaymentCipherDialog dialog) {
				this.bankCode = bankCode;
				this.rechargeAmount = rechargeAmount;
				this.paytk = paytk;
				this.token = token;
				this.dialog = dialog;
			}

			@Override
			protected Void doInBackground(Void... arg0) {
				// TODO Auto-generated method stub
				RequestObject requestObject = new RequestObject();
				requestObject.method = "dkChargeSubmit";
				requestObject.map.put("bankCode", bankCode);
				requestObject.map.put("rechargeAmount", rechargeAmount);
				requestObject.map.put("paytk", paytk);
				requestObject.map.put("token", token);
				String requrestUrl = RequestBuilder.build(requestObject);

				try {
					IjConnect.doRequest(requrestUrl, dc);
					if (dc.code == null) {
						mFailStr = "获取数据异常，请稍后重试";
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						mFailStr = dc.msg;
					}
				} catch (Exception e) {
					mFailStr = "获取数据异常，请稍后重试";
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				// resultFlag = true;
				if (!(TextUtils.isEmpty(mFailStr))) {// fail
					Toast.makeText(context, mFailStr, Toast.LENGTH_LONG).show();
					dialog.dismiss();
					mwebView.stopLoading();
					mProgressBar.setVisibility(View.GONE);
					mLlPaymentCipher.setVisibility(View.GONE);
					mwebView.clearCache(true);
					mwebView.clearHistory();
//					RechargeActivity.instance.setResult(Activity.RESULT_CANCELED);
//					RechargeActivity.instance.finish();
				} else {// success
					Toast.makeText(context, dc.msg, Toast.LENGTH_LONG).show();
					mwebView.stopLoading();
					mProgressBar.setVisibility(View.GONE);
					mLlPaymentCipher.setVisibility(View.GONE);
					mwebView.clearCache(true);
					mwebView.clearHistory();
					dialog.dismiss();
//					RechargeActivity.instance.setResult(Activity.RESULT_OK);
//					RechargeActivity.instance.finish();
				}
			}

		}
	}

}
